package utils

import (
	"crypto/tls"
	"fmt"

	"gopkg.in/gomail.v2"
	"ttsx/server/common/global"
)

func ActiveEmail(username, emailAddr, appName, url, port, token string) (bool, error) {
	// 初始化message对象
	m := gomail.NewMessage()

	// 设置邮件header信息
	m.SetHeader("From", global.App.Config.Email.From)
	m.SetHeader("To", emailAddr)
	m.SetHeader("Subject", global.App.Config.Email.Subject)
	m.SetHeader("Cc", global.App.Config.Email.From)

	active_href := fmt.Sprintf("http://%s:%s/%s/user/active?token=%s", url, port, appName, token)

	// 构建邮件正文格式
	message := `
	Dear: %s
	请在10分钟内点击下面链接, 完成账号的激活：
	%s`
	body := fmt.Sprintf(message, username, active_href)
	global.App.Log.Info(body)

	m.SetBody("text/plain", body)

	d := gomail.NewDialer(
		global.App.Config.Email.SmtpUrl,
		global.App.Config.Email.SmtpPort,
		global.App.Config.Email.From,
		global.App.Config.Email.SmtpCode,
	)

	// 验证SSL协议
	d.TLSConfig = &tls.Config{InsecureSkipVerify: !global.App.Config.Email.IsTLS}

	if err := d.DialAndSend(m); err != nil {
		return false, err
	}
	return true, nil
}
